﻿using Sheep_Breeding.Domain;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Read.Api.DTOSheep;
using Sheep_Breeding.Read.Api.OperationServices.IServices;

namespace Sheep_Breeding.Read.Api.OperationServices.Services
{
    /// <summary>
    /// 羊场管理实现类
    /// </summary>
    public class SheepfarmServices: ISheepfarmServices
    {
        private readonly ILogger<SheepfarmServices> logger;
        private readonly IBaseRepository<Sheepfarm_management> sheepfarm_management;
        private readonly IBaseRepository<Thescalethsheepfarm> thescalethsheepfarm;
        private readonly IBaseRepository<BuildingManagement> buildingManagement;
        private readonly IBaseRepository<House_typeInfo> house_TypeInfo;
        private readonly IBaseRepository<Field_management> field_management;

        public SheepfarmServices(ILogger<SheepfarmServices> logger, IBaseRepository<Sheepfarm_management> sheepfarm_management, IBaseRepository<Thescalethsheepfarm> thescalethsheepfarm,IBaseRepository<BuildingManagement> buildingManagement,IBaseRepository<House_typeInfo> house_typeInfo,IBaseRepository<Field_management> field_management)
        {
            this.logger = logger;
            this.sheepfarm_management = sheepfarm_management;
            this.thescalethsheepfarm = thescalethsheepfarm;
            this.buildingManagement = buildingManagement;
            house_TypeInfo = house_typeInfo;
            this.field_management = field_management;
        }



        /// <summary>
        /// 获取羊场管理数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<List<Sheepfarm_managementDto>>> SearchSheepfarm_management(SearchSheepfarm_managementQueryDto dto)
        {
            try
            {
                var res = new ApiPaging<List<Sheepfarm_managementDto>>();

                //羊场数据
                var sheepfarm_managementinfo = sheepfarm_management.Getlist().Where(x => x.IsDelete.Equals(false));
                //羊场规模
                var thescalethsheepfarminfo = thescalethsheepfarm.Getlist().Where(x => x.IsDelete.Equals(false));

                //查询羊场全称
                if (!string.IsNullOrEmpty(dto.FarmName))
                {
                    sheepfarm_managementinfo = sheepfarm_managementinfo.Where(x => x.FarmName.Contains(dto.FarmName));
                }
                //查找负责人
                if (!string.IsNullOrEmpty(dto.Manager))
                {
                    sheepfarm_managementinfo = sheepfarm_managementinfo.Where(x => x.Manager.Contains(dto.Manager));
                }


                //linp查询（内查询）

                var linp = from a in sheepfarm_managementinfo
                           join b in thescalethsheepfarminfo on a.TheScaleOfSheepfarmId equals b.ThescalethsheepfarmId
                           select new Sheepfarm_managementDto()
                           {
                               SheepfarmId = a.SheepfarmId,
                               FarmCode = a.FarmCode,
                               FarmName = a.FarmName,
                               FarmShortName = a.FarmShortName,
                               TheScaleOfSheepfarmId = a.TheScaleOfSheepfarmId,
                               ThescalethsheepName = b.ThescalethsheepName,
                               CreateDate = a.CreateDate,
                               Manager = a.Manager,
                               Address = a.Address,
                               Department = a.Department,
                               Status = a.Status,
                               Creator = a.Creator,
                               CreateTime = a.CreateTime,
                               Modifier = a.Modifier,
                               ModifyTime = a.ModifyTime,
                               IsDelete = a.IsDelete
                           };

                //分页信息
                res.TotalCount = linp.Count();
                res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / dto.PageSize);
                res.PageData = linp.OrderByDescending(x => x.CreateTime).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToList();

                res.success("获取羊场管理数据成功", null);
                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 查找羊场规模数据
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<Thescalethsheepfarm>>> SearchSheepFiles()
        {
            try
            {
                logger.LogInformation("查找羊场规模数据");

                var res = new ApiResult<List<Thescalethsheepfarm>>();

                var info = thescalethsheepfarm.Getlist().Where(x => x.IsDelete.Equals(false));


                res.code = ApiREunm.Ok;
                res.data = info.ToList();
                res.msg = "查找羊场规模数据成功";

                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 查找栋舍类型
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<House_typeInfo>>> SearchHouse_typeInfo()
        {
            try
            {
                logger.LogInformation("查找栋舍类型操作");

                var res=new ApiResult<List<House_typeInfo>>();

                var info = house_TypeInfo.Getlist().Where(x => x.IsDelete.Equals(false));

                res.success("查找栋舍类型成功", info.ToList());
                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("查找栋舍类型异常" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 查找栋舍管理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiPaging<List<SearchforbuildinginfoDto>>> SearchBuildingManagement(SearchBuildingManagementDto dto)
        {
            try
            {
                logger.LogInformation("查找栋舍管理信息操作");

                var res = new ApiPaging<List<SearchforbuildinginfoDto>>();

                var buildingManagementinfo = buildingManagement.Getlist().Where(x => x.IsDelete.Equals(false));
                var house_TypeInfose= house_TypeInfo.Getlist().Where(x=>x.IsDelete.Equals(false));

                if (dto.House_typeId>0)
                {
                    buildingManagementinfo = buildingManagementinfo.Where(x => x.House_typeId.Equals(dto.House_typeId));
                }

                if (!string.IsNullOrEmpty(dto.House_name))
                {
                    buildingManagementinfo = buildingManagementinfo.Where(x => x.House_name.Contains(dto.House_name));
                }

                if (!string.IsNullOrEmpty(dto.Manager))
                {
                    buildingManagementinfo = buildingManagementinfo.Where(x => x.Manager.Contains(dto.Manager));
                }

                var linp = from a in buildingManagementinfo
                           join b in house_TypeInfose on a.House_typeId equals b.House_typeId
                           select new SearchforbuildinginfoDto()
                           {
                               BuildingId=a.BuildingId,
                               House_typeId=a.House_typeId,
                               DongsheName=b.DongsheName,
                               House_name=a.House_name,
                               Manager=a.Manager,
                               Producer=a.Producer,
                               Status=a.Status,
                               Remarks=a.Remarks,
                               Creator=a.Creator,
                               Create_time=a.Create_time,
                               Modifier=a.Modifier,
                               Modify_time=a.Modify_time,
                               IsDelete=a.IsDelete
                           };

                res.TotalCount= linp.Count();
                res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / dto.PageSize);
                res.PageData = linp.OrderByDescending(x => x.Create_time).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToList();


                res.success("查找栋舍管理信息成功",null);
                return res;
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// 根据栋舍Id查找栏位管理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<List<Field_management>>> SearchField_management(SearchField_managementDto dto)
        {
            try
            {
                logger.LogInformation("查找栏位管理信息操作");

                var res=new ApiPaging<List<Field_management>>();

                var info = field_management.Getlist().Where(x => x.BuildingId.Equals(dto.BuildingId) && x.IsDelete.Equals(false));

                res.TotalCount = info.Count();
                res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / dto.PageSize);
                res.PageData = info.OrderByDescending(x => x.Field).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToList();

                res.success("根据栋舍Id查找栏位管理信息操作",null);
                return res;

                
            }
            catch (Exception ex)
            {

                logger.LogError("查找栏位管理信息异常" + ex.Message);
                throw ex;
            }
        }
    }
}
